<template>
  <div class="cert-container">
    <div ref="actionBtnRef" class="actionBtn flex alignCenter justifyBetween">
      <div>
        <el-button :disabled="!selectArr.length" plain @click="handleClick(7)"
          >考试性质</el-button
        >
        <el-button :disabled="!selectArr.length" plain @click="handleClick(5)"
          >学员申报</el-button
        >
        <el-button plain @click="handleClick(8)" :disabled="!selectArr.length"
          >考试日期</el-button
        >
        <el-button plain @click="handleClick(6)">成绩导入</el-button>
        <el-button :disabled="!selectArr.length" plain @click="handleClick(4)"
          >导出</el-button
        >
      </div>

      <span class="flex alignCenter">
        <el-dropdown style="cursor: pointer; margin-right: 10px">
          <span class="el-dropdown-link flex alignCenter">
            <el-icon>
              <Sort />
            </el-icon>
            <div class="shrink">
              {{
                sortArr[
                  proxy.$utils.findIndexByField(
                    sortArr,
                    "value",
                    formInline.sort
                  )
                ].name
              }}
            </div>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item
                @click="setSort(item.value)"
                v-for="(item, index) in sortArr"
                :key="index"
                >{{ item.name }}</el-dropdown-item
              >
            </el-dropdown-menu>
          </template>
        </el-dropdown>

        <el-select
          v-model="formInline.isSubmit"
          clearable
          placeholder="人社刷卡"
          @clear="search"
          @change="search"
          class="examSearch"
        >
          <el-option label="是" :value="1" />
          <el-option label="否" :value="0" />
        </el-select>

        <el-select
          v-model="formInline.examType"
          clearable
          placeholder="考试性质"
          @clear="search"
          @change="search"
          class="examSearch"
        >
          <el-option label="正考" :value="1" />
          <el-option label="补考" :value="0" />
        </el-select>

        <dictSelect
          class="examSearch"
          @fatherMethods="search"
          val="dict_label"
          v-model="formInline.affiliation_dictLabel"
          dictCode="registration_affiliation"
          multiple="1"
          placeholder="报名所属"
        ></dictSelect>

        <el-select
          collapse-tags
          collapse-tags-tooltip
          :max-collapse-tags="1"
          multiple
          v-model="formInline.isExamination"
          clearable
          placeholder="获证情况"
          @clear="search"
          @change="search"
          class="examSearch"
        >
          <el-option label="未获证" :value="0" />
          <el-option label="获证" :value="1" />
          <el-option label="未出考" :value="2" />
          <el-option label="空白" :value="-1" />
        </el-select>

        <el-input
          class="examSearch"
          v-model="formInline.keyWords"
          @clear="search"
          @change="search"
          clearable
          placeholder="搜索姓名/联系方式"
        >
          <template #append>
            <el-button icon="Search" @click="search" />
          </template>
        </el-input>

        <el-input
          @clear="search"
          @change="search"
          clearable
          v-model="formInline.identityCardOrEnterprise"
          placeholder="搜索身份证/所在企业"
          class="examSearch"
        >
          <template #append>
            <el-button icon="Search" @click="search" />
          </template>
        </el-input>
      </span>
    </div>
    <el-table
      @selection-change="handleSelectionChange"
      :max-height="tableMaxHeight"
      ref="multipleTableRef"
      v-loading="loading"
      :data="tableParams.rows"
    >
      <el-table-column type="selection" width="55" fixed="left" />
      <el-table-column label="状态" prop="name" width="55" fixed="left">
        <template #default="scope">
          <el-tooltip
            class="box-item"
            v-if="scope.row.userState == 0"
            effect="dark"
            :content="`停课日期 ${scope.row.suspensionClassDate}`"
            placement="top"
          >
            <div style="color: #8530f5">停课</div>
          </el-tooltip>
          <div class="status-icon" v-else-if="scope.row.userState == 2">
            <img
              src="https://shdiditazi.oss-cn-shanghai.aliyuncs.com/image/6ec5b77ded30e5ff51a211dd703a097f.png"
              alt=""
            />
          </div>
          <div v-else class="status-icon">
            <img src="@/assets/images/checkIcon.png" alt="" />
          </div>
        </template>
      </el-table-column>
      <el-table-column type="index" width="50" label="序号" fixed="left">
        <template #default="scope">
          {{
            (formInline.pageIndex - 1) * formInline.pageSize + scope.$index + 1
          }}
        </template>
      </el-table-column>
      <el-table-column label="姓名" width="70" fixed="left">
        <template #default="scope">
          {{ field_format(scope.row, "name") }}
        </template>
      </el-table-column>
      <el-table-column label="联系方式" width="110" fixed="left">
        <template #default="scope">
          {{ field_format(scope.row, "mobile") }}
        </template>
      </el-table-column>
      <el-table-column
        label="报名所属"
        width="150"
        prop="affiliation_dictLabel"
        show-overflow-tooltip
      />
      <!-- <el-table-column label="课程名称" width="250" show-overflow-tooltip>
        <template #default="scope">
          {{ curriculumName(scope.row.curriculum_id) }}
        </template>
      </el-table-column> -->
      <el-table-column label="性别" prop="name" width="55">
        <template #default="scope">
          {{ getGenderByIdCard(scope.row) }}
        </template>
      </el-table-column>
      <el-table-column label="身份证号" width="165">
        <template #default="scope">
          {{ field_format(scope.row, "identityCard") }}
        </template>
      </el-table-column>
      <el-table-column
        label="所在企业名称"
        show-overflow-tooltip
        min-width="200"
      >
        <template #default="scope">
          {{ field_format(scope.row, "enterprise") }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="就业状态" width="80" show-overflow-tooltip>
        <template #default="scope">
          {{field_format(scope.row,'employed_Status')}}
        </template>
      </el-table-column> -->
      <el-table-column label="人社刷卡" width="80">
        <template #default="scope">
          <div v-if="scope.row.isSubmit == 1" style="color: #3b9a66">是</div>
          <div v-else>否</div>
        </template>
      </el-table-column>
      <el-table-column prop="order_Info.price" label="订单金额" width="120">
        <template #default="scope">
          <div class="flex alignCenter">
            {{ proxy.$utils.formatNumber(scope.row.order_Info.displayPrice) }}
            <div
              class="minus classStatus"
              v-if="scope.row.order_Info.status == 10"
            >
              减
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="报名状态" width="120" align="center">
        <template #default="scope">
          <div v-if="scope.row.order_Info.status">
            <el-tag
              type="danger"
              v-if="
                scope.row.order_Info.status == 1 &&
                scope.row.order_Info.rejectMsg
              "
              >已驳回</el-tag
            >
            <el-tag
              v-else
              :color="counter.tagBgColor(scope.row.order_Info.status)"
            >
              <div
                :style="{
                  color: counter.tagColor(scope.row.order_Info.status),
                }"
              >
                {{ status_format(scope.row.order_Info.status) }}
              </div>
            </el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="考试性质" width="80">
        <template #default="scope">
          <div
            v-if="scope.row.examType == 0"
            class="bold"
            style="color: #409eff"
          >
            补考
          </div>
          <div v-else class="bold" style="color: #67c23a">正考</div>
        </template>
      </el-table-column>
      <el-table-column
        prop="declarationBatchNumber"
        label="申报批次号"
        width="150"
      />
      <el-table-column prop="examDate" label="考试日期" width="100" />
      <el-table-column
        prop="theory"
        label="理论成绩"
        width="100"
        align="center"
      >
        <template #default="scope">
          <el-input
            v-model="scope.row.theory"
            v-if="isEditScore"
            placeholder="请输入"
            @change="handleEditScore(scope.row)"
          />
          <div v-else>{{ scope.row.theory }}</div>
        </template>
      </el-table-column>
      <el-table-column
        prop="practicalTraining"
        label="实训成绩"
        width="100"
        align="center"
      >
        <template #default="scope">
          <el-input
            v-model="scope.row.practicalTraining"
            v-if="isEditScore"
            placeholder="请输入"
            @change="handleEditScore(scope.row)"
          />
          <div v-else>{{ scope.row.practicalTraining }}</div>
        </template>
      </el-table-column>
      <el-table-column label="获证情况" width="100">
        <template #default="scope">
          <div v-if="scope.row.hasOwnProperty('isExamination')">
            <div v-if="scope.row.isExamination == 0" style="color: #a51d1b">
              未获证
            </div>
            <div
              v-else-if="scope.row.isExamination == 1"
              style="color: #3b9a66"
            >
              获证
            </div>
            <div
              v-else-if="scope.row.isExamination == 2"
              style="color: #f5c73c"
            >
              未出考
            </div>
          </div>
          <div v-else>-</div>
        </template>
      </el-table-column>
      <el-table-column
        label="证书编号"
        align="center"
        prop="certificateNumber"
        width="200"
      >
        <template #default="scope">
          <el-input
            v-model="scope.row.certificateNumber"
            v-if="isEditScore"
            placeholder="请输入"
            @change="handleEditScore(scope.row)"
          />
          <div v-else>{{ scope.row.certificateNumber }}</div>
        </template>
      </el-table-column>
      <el-table-column label="证书" align="center" width="80">
        <template #default="scope">
          <el-button
            @click="showPreview(scope.row)"
            v-if="scope.row.certificateUrl"
            type="primary"
            icon="View"
            circle
            size="small"
          ></el-button>
          <el-button
            @click="uploadClick(scope.row)"
            v-else
            type="primary"
            icon="Upload"
            circle
            size="small"
            :disabled="canUploadCertificate(scope.row)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-if="tableParams['total']"
      :total="tableParams['total']"
      v-model:page="formInline.pageIndex"
      v-model:limit="formInline.pageSize"
      @pagination="getInfo"
    />

    <!-- 上传证书 -->
    <uploadImage
      ref="uploadImageRef"
      v-model="certificateParams.certificateUrl"
      v-show="false"
    ></uploadImage>

    <!-- 预览证书 -->
    <el-dialog
      v-model="previewVisible"
      title="预览"
      width="800px"
      append-to-body
      :before-close="onClose"
    >
      <div class="flex justifyEnd alignCenter" style="margin-bottom: 10px">
        <el-button
          type="primary"
          @click="proxy.$refs.uploadImageRef.inputClick()"
          >重新上传</el-button
        >
      </div>
      <img
        :src="dialogImageUrl"
        style="display: block; max-width: 100%; margin: 0 auto"
      />
    </el-dialog>

    <!-- 学员申报 -->
    <studentDeclaration
      ref="studentDeclarationRef"
      @fatherMethods="getInfo"
    ></studentDeclaration>

    <!-- 成绩导入 -->
    <input
      type="file"
      @change="handleFileImport"
      v-show="false"
      ref="fileClick"
    />
  </div>
</template>

<script setup lang="ts">
import studentDeclaration from "@/views/courseManage/components/studentDeclaration.vue";
const { proxy } = getCurrentInstance();
import useCounterStore from "@/store/counter";
const counter = useCounterStore();
let props = defineProps(["info"]);

let tabs = ref([
  { name: "待审核", value: 1 },
  { name: "审核未通过", value: 3 },
  { name: "支付尾款", value: 8 },
  { name: "报名成功", value: 2 },
  { name: "优惠减免", value: 10 },
  { name: "已退款", value: 4 },
  { name: "部分退款", value: 9 },
  { name: "已开票", value: 7 },
]);
let sortArr = ref([
  { name: "按姓名默认排序", value: "userPinyin" },
  { name: "按报名所属排序", value: "affiliationPinyin" },
  { name: "按所在企业名称排序", value: "enterprisePinyin" },
]);
let previewVisible = ref(false);
let formInline = ref({
  pageIndex: 1,
  pageSize: 500,
  classId: "",
  keyWords: "",
  sort: "userPinyin",
  identityCardOrEnterprise: "",
  affiliation_dictLabel: "",
  isExamination: [],
  isSubmit: null,
  examType: null,
});
let loading = ref(false);
let tableParams = ref({});
let dialogImageUrl = ref("");
let certificateParams = ref({
  _id: "",
  certificateUrl: "",
});
let selectArr = ref([]);
let actionBtnHeight = ref(0);
let selectedRow = ref([]);
let isEditScore = ref(false); //是否编辑成绩

let tableMaxHeight = computed(() => {
  let hei =
    window.innerHeight -
    84 -
    counter.pageHeight -
    110 -
    actionBtnHeight.value -
    counter.classCardHeight;
  return `${hei}px`;
});

onMounted(() => {
  search();
  actionBtnHeight.value = proxy.$refs.actionBtnRef.offsetHeight;
  console.log("actionBtnHeight", actionBtnHeight.value);
});

function curriculumName(id) {
  let index = proxy.$utils.findIndexByField(counter.courseList, "_id", id);
  return counter.courseList[index].name;
}

function setSort(value) {
  formInline.value.sort = value;
  search();
}

function showPreview(e) {
  dialogImageUrl.value = e.certificateUrl;
  certificateParams.value._id = e._id;
  previewVisible.value = true;
}

function uploadClick(e) {
  certificateParams.value._id = e._id;
  proxy.$refs.uploadImageRef.inputClick();
}

function search() {
  formInline.value.pageIndex = 1;
  getInfo();
}

function canUploadCertificate(e) {
  let aa = true;
  if (e.hasOwnProperty("isExamination") && e.isExamination == 1) {
    aa = false;
  }
  return aa;
}

function getGenderByIdCard(item) {
  let row = item.source ? item.user_data : item.order_Info.orderUserInfo;
  let idCard = row.identityCard;
  if (!idCard || idCard.length !== 18) return "-";
  const sexCode = idCard.charAt(16);
  const gender = parseInt(sexCode, 10) % 2 === 0 ? "女" : "男";
  return gender;
}

function field_format(item, key) {
  let row = item.source ? item.user_data : item.order_Info.orderUserInfo;
  if (key == "enterprise") return counter.showEnterprise(row, key);
  return row[key];
}

async function handleEditScore(e: any) {
  let data = {
    _id: e._id,
    theory: e.theory,
    certificateNumber: e.certificateNumber,
    practicalTraining: e.practicalTraining,
  };
  await proxy.$apis.classStudent({
    type: "update",
    data,
  });
  proxy.$utils.showToast("修改成功");
  getInfo();
}

async function getInfo() {
  try {
    loading.value = true;
    if (!props.info._id) return;
    formInline.value.classId = props.info._id;
    formInline.value.keyWords = formInline.value.keyWords.trim();
    tableParams.value = await proxy.$apis.classStudent({
      type: "list",
      data: formInline.value,
    });
    console.log("tableParams.value", tableParams.value);
  } catch (error) {
  } finally {
    loading.value = false;
  }
}

function onClose() {
  certificateParams.value = { _id: "", certificateUrl: "" };
  dialogImageUrl.value = "";
  previewVisible.value = false;
}

async function updateClassUserInfo() {
  await proxy.$apis.classStudent({
    type: "update",
    data: certificateParams.value,
  });
  proxy.$utils.showToast("上传成功");
  getInfo();
  certificateParams.value = { _id: "", certificateUrl: "" };
}

function handleSelectionChange(e) {
  selectedRow.value = e;
  selectArr.value = [];
  e.forEach((element) => {
    selectArr.value.push(element._id);
  });
}

async function handleClick(num, type?) {
  try {
    switch (num) {
      case 4: //导出学员
        exportStudents();
        break;
      case 5:
        proxy.$refs.studentDeclarationRef.open(5, selectArr.value);
        break;
      case 6:
        //下载模板
        counter.downLoadTemplate("class-student-achievement", "成绩导入模板");
        proxy.$refs.fileClick.click();
        break;
      case 7: //考试性质
        proxy.$refs.studentDeclarationRef.open(6, selectArr.value);
        break;
      case 8: //考试日期
        proxy.$refs.studentDeclarationRef.open(7, selectArr.value);
        break;
    }
  } catch (error) {
    console.log("学员操作报错", error);
  }
}

//导出学员
async function exportStudents() {
  let rows = selectedRow.value;
  let data = <any>[];
  let cols = []; //设置表头样式
  rows.forEach((element, index) => {
    cols.push({ wch: 20 });
    data.push({
      序号: index + 1,
      状态: element.userState == 0 ? "停课" : "正常",
      姓名: field_format(element, "name"),
      联系方式: field_format(element, "mobile"),
      报名所属: affiliation_format(element),
      //课程名称: curriculumName(element.curriculum_id),
      性别: getGenderByIdCard(element),
      身份证号: field_format(element, "identityCard"),
      所在企业名称: field_format(element, "enterprise"),
      //就业状态: field_format(element, "employed_Status"),
      //累计工作年限: field_format(element, "workYears"),
      //最高学历: field_format(element, "education"),
      //毕业专业: field_format(element, "graduationMajor"),
      //毕业院校: field_format(element, "school"),
      订单金额: proxy.$utils.formatNumber(element.order_Info.displayPrice),
      报名状态: status_format(element.order_Info.status),
      考试性质: element.examType == 0 ? "补考" : "正考",
      //备注: element.remark,
      申请批次号: element.declarationBatchNumber,
      理论成绩: element.theory,
      实训成绩: element.practicalTraining,
      获证情况: certificationStatus(element),
      证书编号: element.certificateNumber,
      //进班日期: proxy.$utils.dateTimeFormateFn(element._add_time),
    });
  });
  let query = { jsonData: data, cols };
  await proxy.$utils.exportToExcel(query, "考试信息");
}

function certificationStatus(e) {
  if (!e.hasOwnProperty("isExamination")) return "-";
  if (e.isExamination == 0) {
    return "未获证";
  } else if (e.isExamination == 1) {
    return "获证";
  } else if (e.isExamination == 2) {
    return "未出考";
  }
}

function status_format(e) {
  if (e == 8) {
    return "支付尾款";
  } else if (e == 10) {
    return "报名成功";
  } else {
    for (let index = 0; index < tabs.value.length; index++) {
      const element = tabs.value[index];
      if (element.value == e) return element.name;
    }
  }
}

function affiliation_format(row) {
  if (!row.affiliation) return "-";
  let key;
  let list = counter.dictOptions["registration_affiliation"];
  if (proxy.$utils.isString(row.affiliation)) {
    key = row.affiliation;
  } else if (proxy.$utils.isJsonArray(row.affiliation) == "arr") {
    key = row.affiliation[0];
  }
  let current = proxy.$utils.findIndexByField(list, "dict_code", key);
  if (current != -1) return list[current].dict_label;
  return "-";
}

async function handleFileImport(event) {
  try {
    const files = event.target.files;

    //上传模板
    //return counter.importTemplate(files, "class-student-achievement");

    let file = files[0];
    let resp = await proxy.$utils.fileToJson(file);

    let list = [];
    for (let index = 0; index < resp.length; index++) {
      const element = resp[index];
      if (index) {
        list.push({
          idCard: element[1],
          theory: element[2], //理论
          practicalTraining: element[3], //实训
          certificateNumber: element[4], //证书编号
        });
      }
    }
    let res = await proxy.$apis.classStudent({
      type: "scoreImport",
      data: { list, classId: props.info._id },
    });

    if (!res.errorList.length) proxy.$utils.showToast("导入成功");
    if (res.errorList.length < resp.length) {
      let errs = <string>[];
      res.errorList.forEach((element) => {
        errs.push(element.error);
      });
      let msg =
        "导入成功，以下学员导入失败：" +
        errs.toString() +
        "," +
        "是否手动修改这些学员？";
      const confirmTips = await proxy.$utils.confirmTips(msg);
      if (!confirmTips) return;
      isEditScore.value = true;
    }

    getInfo();
  } catch (error) {
  } finally {
    event.target.value = "";
  }
}

watch(
  () => certificateParams.value.certificateUrl,
  (newValue, oldValue) => {
    if (newValue) {
      if (previewVisible.value) dialogImageUrl.value = newValue;
      updateClassUserInfo();
    }
  },
  { immediate: true, deep: true }
);
</script>

<style lang="scss" scoped>
.actionBtn {
  margin-bottom: 15px;
}
.examSearch {
  width: 200px;
  margin-right: 10px;
}
.classStatus {
  border-radius: 50%;
  margin-left: 5px;
  width: 18px;
  height: 18px;
  line-height: 18px;
  text-align: center;
  color: #97999e;
  border: 1px solid #97999e;
  cursor: pointer;
  font-size: 12px;
  font-weight: bold;
}
.minus {
  color: #f66604 !important;
  border: 1px solid #f66604 !important;
}
</style>
